package com.example.blockbreaker;

import com.example.blockbreaker.R;
import com.google.android.material.button.MaterialButton;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.HapticFeedbackConstants;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.Navigation;

import java.util.Locale;

public class CountDownFragment extends Fragment {
    private CountDownViewModel viewModel;
    private TextView timeText, moneyText, cigsText;

    private MaterialButton btnCravingHelp;
    private CravingHelper cravingHelper;
    private SharedPreferences prefs;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_countdown, container, false);

        timeText = view.findViewById(R.id.time_text);
        moneyText = view.findViewById(R.id.money_saved_text);
        cigsText = view.findViewById(R.id.cigs_avoided_text);

        // 初始化组件
        btnCravingHelp = view.findViewById(R.id.btn_craving_help);
        cravingHelper = new CravingHelper();
        prefs = requireActivity().getSharedPreferences("QuitSmokePrefs", Context.MODE_PRIVATE);

        setupCravingButton();
        viewModel = new ViewModelProvider(this).get(CountDownViewModel.class);
        SharedPreferences prefs = requireActivity().getSharedPreferences("QuitSmokePrefs", Context.MODE_PRIVATE);
        viewModel.init(prefs);

        observeViewModel();

        return view;
    }

    private void setupCravingButton() {
        btnCravingHelp.setOnClickListener(v -> {
            // 1. 显示帮助选项对话框
            showCravingHelpDialog();

            // 2. 记录烟瘾发作事件
            recordCravingEvent();
        });
    }

    private void showCravingHelpDialog() {
        String[] actions = {
                "开始呼吸练习",
                "获取分散注意力活动",
                "查看戒烟好处提醒",
                "联系支持伙伴"
        };

        int[] icons = {
                R.drawable.ic_breath,
                R.drawable.ic_activity,
                R.drawable.ic_motivation,
                R.drawable.ic_support
        };

        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
        builder.setTitle("需要帮助抵抗烟瘾吗？");
        builder.setAdapter(new ArrayAdapterWithIcons(requireContext(), actions, icons), (dialog, which) -> {
            switch (which) {
                case 0:
                    startBreathingExercise();
                    break;
                case 1:
                    suggestDistractionActivity();
                    break;
                case 2:
                    showMotivationalMessage();
                    break;
                case 3:
                    contactSupportPartner();
                    break;
            }
        });
        builder.setNegativeButton("稍后", null);
        builder.show();
    }

    // 自定义带图标的ArrayAdapter
    private static class ArrayAdapterWithIcons extends ArrayAdapter<String> {
        private final int[] icons;

        public ArrayAdapterWithIcons(Context context, String[] items, int[] icons) {
            super(context, android.R.layout.select_dialog_item, items);
            this.icons = icons;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = super.getView(position, convertView, parent);
            TextView textView = (TextView) view;
            textView.setCompoundDrawablesWithIntrinsicBounds(icons[position], 0, 0, 0);
            textView.setCompoundDrawablePadding(32);
            return view;
        }
    }

    private void observeViewModel() {
        viewModel.getSmokeFreeTime().observe(getViewLifecycleOwner(), time -> {
            String formattedTime = formatTime(time);
            timeText.setText(formattedTime);
        });

        viewModel.getMoneySaved().observe(getViewLifecycleOwner(), money -> {
            moneyText.setText(String.format("节省金额: $%.2f", money));
        });

        viewModel.getCigarettesAvoided().observe(getViewLifecycleOwner(), cigs -> {
            cigsText.setText("避免吸烟: " + cigs + "支");
        });
    }

    private void startBreathingExercise() {
        // 启动呼吸练习Activity
        Intent intent = new Intent(requireActivity(), BreathingActivity.class);
        startActivity(intent);

        // 记录事件
        logHelpAction("breathing_exercise");
    }

    private void suggestDistractionActivity() {
        String activity = CravingHelper.getRandomDistraction();
        String motivationalQuote = CravingHelper.getRandomMotivationalQuote();

        new AlertDialog.Builder(requireContext())
                .setTitle("试试这个活动:")
                .setMessage(activity + "\n\n" + motivationalQuote)
                .setPositiveButton("好的", (dialog, which) -> {
                    // 用户确认后记录
                    logHelpAction("distraction_activity");
                })
                .setNegativeButton("换一个", (dialog, which) -> suggestDistractionActivity())
                .show();
    }

    private void showMotivationalMessage() {
        // 获取戒烟时间数据
        long quitTimestamp = prefs.getLong("quit_timestamp", 0);
        long currentTime = System.currentTimeMillis();

        // 计算准确的戒烟时间（防止除零错误）
        if (quitTimestamp == 0 || quitTimestamp > currentTime) {
            // 处理未设置戒烟时间或未来时间的情况
            showDefaultMotivationalMessage();
            return;
        }

        // 精确计算戒烟时长
        long smokeFreeMillis = currentTime - quitTimestamp;
        int daysQuit = (int) (smokeFreeMillis / (1000 * 60 * 60 * 24));
        int hoursQuit = (int) ((smokeFreeMillis % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));

        // 计算健康益处（基于科学研究）
        String healthBenefits = calculateHealthBenefits(daysQuit, hoursQuit);

        // 计算节省的金钱
        int dailyCigs = prefs.getInt("daily_cigs", 10);
        float packPrice = prefs.getFloat("pack_price", 5.0f);
        double moneySaved = (dailyCigs / 20.0) * packPrice * daysQuit;

        // 构建消息
        String message = String.format(Locale.getDefault(),
                "你已经成功戒烟 %d 天 %d 小时！\n\n" +
                        "%s\n\n" +
                        "节省了 $%.2f\n" +
                        "避免了 %d 支香烟\n\n" +
                        "%s",
                daysQuit, hoursQuit,
                healthBenefits,
                moneySaved,
                dailyCigs * daysQuit,
                CravingHelper.getRandomMotivationalQuote());

        new AlertDialog.Builder(requireContext())
                .setTitle("你的身体正在恢复！")
                .setMessage(message)
                .setPositiveButton("继续坚持", null)
                .show();
    }

    private String calculateHealthBenefits(int daysQuit, int hoursQuit) {
        StringBuilder benefits = new StringBuilder();

        // 基于WHO和美国癌症协会的戒烟时间表
        if (hoursQuit >= 8 && daysQuit == 0) {
            benefits.append("✓ 血氧水平恢复正常\n");
        }
        if (daysQuit >= 1) {
            benefits.append("✓ 体内尼古丁完全清除\n");
        }
        if (daysQuit >= 2) {
            benefits.append("✓ 味觉和嗅觉开始改善\n");
        }
        if (daysQuit >= 3) {
            benefits.append("✓ 呼吸更顺畅\n");
        }
        if (daysQuit >= 14) {
            benefits.append("✓ 血液循环改善\n");
        }
        if (daysQuit >= 30) {
            benefits.append("✓ 肺部功能提升30%\n");
        }
        if (daysQuit >= 90) {
            benefits.append("✓ 咳嗽和喘息减少\n");
        }
        if (daysQuit >= 180) {
            benefits.append("✓ 心脏病风险显著降低\n");
        }
        if (daysQuit >= 365) {
            benefits.append("✓ 冠心病风险减半\n");
        }
        if (daysQuit >= 1825) { // 5年
            benefits.append("✓ 中风风险降至非吸烟者水平\n");
        }
        if (daysQuit >= 3650) { // 10年
            benefits.append("✓ 肺癌风险降低50%\n");
        }

        if (benefits.length() == 0) {
            return "✓ 你刚刚开始戒烟，最困难的阶段已经过去！";
        }
        return benefits.toString();
    }

    private void showDefaultMotivationalMessage() {
        new AlertDialog.Builder(requireContext())
                .setTitle("坚持下去！")
                .setMessage("每次抵抗烟瘾都是对身体的一次修复\n\n" +
                        CravingHelper.getRandomMotivationalQuote())
                .setPositiveButton("我明白了", null)
                .show();
    }
    private void contactSupportPartner() {
        String supportContact = prefs.getString("support_contact", "");

        if (!supportContact.isEmpty()) {
            Intent intent = new Intent(Intent.ACTION_SENDTO);
            intent.setData(Uri.parse("smsto:" + supportContact));
            intent.putExtra("sms_body", "我现在特别想抽烟，能给我些鼓励吗？");
            startActivity(intent);
        } else {
            new AlertDialog.Builder(requireContext())
                    .setTitle("尚未设置支持伙伴")
                    .setMessage("请在设置中添加支持伙伴的联系方式")
                    .setPositiveButton("去设置", (d, w) -> {
                        // 导航到设置界面
                        Navigation.findNavController(requireView())
                                .navigate(R.id.nav_settings);
                    })
                    .setNegativeButton("取消", null)
                    .show();
        }

        logHelpAction("contact_support");
    }

    private void recordCravingEvent() {
        // 获取当前时间
        long currentTime = System.currentTimeMillis();

        // 获取SharedPreferences编辑器
        SharedPreferences.Editor editor = prefs.edit();

        // 更新最后一次烟瘾发作时间
        editor.putLong("last_craving_time", currentTime);

        // 增加烟瘾发作计数
        int cravingCount = prefs.getInt("craving_count", 0) + 1;
        editor.putInt("craving_count", cravingCount);

        // 计算距离上次发作的时间间隔
        long lastCravingTime = prefs.getLong("last_craving_time", 0);
        if (lastCravingTime > 0) {
            long interval = currentTime - lastCravingTime;
            editor.putLong("last_craving_interval", interval);
        }

        editor.apply();

        // 可以在这里添加分析或日志记录
        Log.d("CravingEvent", "User experienced craving at " + currentTime);
    }

    private void logHelpAction(String actionType) {

        // 或者使用本地存储
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString("last_help_action", actionType);
        editor.putLong("last_help_time", System.currentTimeMillis());
        editor.apply();
    }

    private void performHapticFeedback() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            btnCravingHelp.performHapticFeedback(HapticFeedbackConstants.CONFIRM);
        } else {
            btnCravingHelp.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
        }
    }
    private String formatTime(long millis) {
        long seconds = millis / 1000;
        long minutes = seconds / 60;
        long hours = minutes / 60;
        long days = hours / 24;

        return String.format(Locale.getDefault(),
                "戒烟时间: %d天 %02d:%02d:%02d",
                days, hours % 24, minutes % 60, seconds % 60);
    }
}